package com.example.canteen.dao.impl;

import com.example.canteen.dao.CExceptionDao;
import com.example.canteen.domain.CException;
import com.example.canteen.util.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class CExceptionDaoImpl implements CExceptionDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public CException findById(int id) {
        CException cException = null;
        String sql = "SELECT eid,exception_type,exception_info FROM exception WHERE eid=?";
        try{
            cException =template.queryForObject(sql,new BeanPropertyRowMapper<CException>(CException.class),id);

        }catch (Exception e){

        }
        return cException;
    }

    @Override
    public CException findByTypeAndInfo(String exceptionType,String exceptionInfo) {
        String sql = "SELECT eid,exception_type,exception_info FROM exception WHERE exception_type=? and exception_info=?";
        CException cException = null;
        try {
            cException = template.queryForObject(sql,new BeanPropertyRowMapper<CException>(CException.class),exceptionType,exceptionInfo);
        }catch (Exception e){

        }
        return cException;
    }

    @Override
    public List<CException> findByCanteenId(int cid) {
        String sql = "SELECT exception.eid,exception_type,exception_info " +
                "FROM exception,canteen_exception WHERE canteen_exception.`cid`=? AND canteen_exception.`eid`=exception.`eid`";
        return template.query(sql, new BeanPropertyRowMapper<CException>(CException.class),cid);
    }

    @Override
    public List<CException> findAll() {
        String sql = "SELECT eid,exception_type,exception_info FROM exception ";
        return template.query(sql, new BeanPropertyRowMapper<CException>(CException.class));
    }


    @Override
    public int delete(int id) {
        String sql = "DELETE FROM exception WHERE eid=?";
        return template.update(sql,id);
    }

    @Override
    public void save(CException cException) {
        String sql = "insert into exception(exception_type,exception_info) value(?,?)";
        template.update(sql, cException.getExceptionType(),
                cException.getExceptionInfo());

    }

    @Override
    public int update(CException cException) {
        String sql = "UPDATE exception SET exception_type=?,exception_info=? WHERE eid=?";
        return template.update(sql,cException.getExceptionType(),
                cException.getExceptionInfo(),cException.getEid());

    }
}
